# scripts/process_dependency_file.py
import os
from algorithm.models.tag_dependency import TagDependency
from django.conf import settings
def process_dependency_file():

    # 读取 static/data/dependencies.txt 文件并创建/更新 TagDependency。
    # 构建文件路径，使用 settings.BASE_DIR 来动态获取项目的根目录路径
    file_path = os.path.join(settings.BASE_DIR, 'static', 'data', 'dependencies.txt')
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            for line in file:
                # 移除行内注释部分
                line = line.split('#', 1)[0]
                # 移除行首尾的空白字符
                line = line.strip()

                # 忽略空行
                if not line:
                    continue

                # 将行按空格拆分
                parts = line.split()

                if len(parts) < 2:
                    print(f"Invalid line format, skipping: {line}")
                    continue

                # 提取 source_tag_index 和 target_tag_index
                source_tag_index = int(parts[0])
                target_tag_index = int(parts[1])

                # 提取 weight，若无则使用默认值 1.0
                if len(parts) == 3:
                    weight = float(parts[2])
                else:
                    weight = 1.0

                # 调用 TagDependency 的 create_or_update 方法
                TagDependency.create_or_update(source_tag_index, target_tag_index, weight)

    except FileNotFoundError:
        print(f"File not found: {file_path}")
    except Exception as e:
        print(f"Error processing file: {e}")
